﻿using System.Reflection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SqlSugar;

namespace Common.ORM.Extensions
{
    /// <summary>
    /// CodeFirs同步数据库
    /// </summary>
    public class CodeFirstHostedService:IHostedService
    {
        private readonly ILogger _logger;
        private readonly ISqlSugarClient db;
        private readonly IConfiguration _configuration;

        /// <summary>Initializes a new instance of the <see cref="T:System.Object" /> class.</summary>
        public CodeFirstHostedService(ILogger<CodeFirstHostedService> logger, ISqlSugarClient sqlSugarClient, IConfiguration configuration)
        {
            _logger = logger;
            db = sqlSugarClient;
            _configuration = configuration;
        }

        /// <summary>
        /// Triggered when the application host is ready to start the service.
        /// </summary>
        /// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
        public Task StartAsync(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            Assembly modelAssembly = Assembly.Load("sixgod.Model");
            var models = modelAssembly.GetExportedTypes().ToList();

            foreach (var item in models)
            {
                if (item.GetCustomAttribute<SugarTable>() != null)
                {
                    db.CodeFirst.SplitTables().InitTables(item);
                }
            }

            return Task.CompletedTask;
        }

        /// <summary>
        /// Triggered when the application host is performing a graceful shutdown.
        /// </summary>
        /// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            return null;
        }
    }
}
